package com.hb.trade.server.project.section.service.raw.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationThirdMapper;
import com.hb.core.pojo.project.file.entity.BidFileInfo;
import com.hb.core.pojo.project.file.mapper.BidFileInfoMapper;
import com.hb.core.pojo.project.opening.entity.OpeningBidTender;
import com.hb.core.pojo.project.opening.mapper.OpeningBidTenderMapper;
import com.hb.core.pojo.project.section.dto.BidSectionOfferDTO;
import com.hb.core.pojo.project.section.dto.TradeSecondQuotationBidInfoDto;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.BidSectionOffer;
import com.hb.core.pojo.project.section.entity.TradeSecondQuotationBidInfo;
import com.hb.core.pojo.project.section.mapper.BidSectionMapper;
import com.hb.core.pojo.project.section.mapper.BidSectionOfferMapper;
import com.hb.core.pojo.project.section.mapper.TradeSecondQuotationBidInfoMapper;
import com.hb.trade.server.project.section.service.raw.BidSectionOfferService;
import com.hb.trade.server.project.section.service.raw.TradeSecondQuotationBidInfoService;
import com.hb.trade.server.project.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 二次报价标段信息表 服务实现类
 * </p>
 *
 * @author fengbin
 * @since 2022-02-21
 */
@Slf4j
@Service
public class TradeSecondQuotationBidInfoServiceImpl extends ServiceImpl<TradeSecondQuotationBidInfoMapper, TradeSecondQuotationBidInfo> implements TradeSecondQuotationBidInfoService {

    protected final OpeningBidTenderMapper openingBidTenderMapper;
    protected final BidSectionOfferService bidSectionOfferService;
    protected final BidSectionOfferMapper bidSectionOfferMapper;

    @Resource
    private BidSectionMapper bidSectionMapper;
    @Resource
    private BidFileInfoMapper bidFileInfoMapper;
    @Resource
    private EvaluationThirdMapper evaluationThirdMapper;

    public TradeSecondQuotationBidInfoServiceImpl(OpeningBidTenderMapper openingBidTenderMapper,
                                                  BidSectionOfferMapper bidSectionOfferMapper,
                                                  BidSectionOfferService bidSectionOfferService
    ) {
        this.openingBidTenderMapper = openingBidTenderMapper;
        this.bidSectionOfferMapper = bidSectionOfferMapper;
        this.bidSectionOfferService = bidSectionOfferService;

    }


    /**
     * Description: 根据标段id初始化报价信息
     *
     * @param tradeSecondQuotationBidInfoDto
     * @author: fengbin
     * @date: 2022/2/21 11:30
     * @return: java.util.List<com.hb.core.pojo.project.section.dto.TradeSecondQuotationBidInfoDto>
     */
    @Override
    public List<TradeSecondQuotationBidInfoDto> initFirstOfferInfo(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfoDto) {
        //根据标段id从一览表中查询企业的报价，当做首次报价保 存到数据库
        List<BidSectionOfferDTO> bidSectionOfferDTOS = listFirstBidSectionOfferInfo(tradeSecondQuotationBidInfoDto);
        //新增二次报价表段表
        tradeSecondQuotationBidInfoDto.setTurns(1);
        tradeSecondQuotationBidInfoDto.setCreateTime(LocalDateTime.now());
        baseMapper.insert(tradeSecondQuotationBidInfoDto);
        //保存报价
        TradeSecondQuotationBidInfo secondQuotationBidInfo = selectSecQuoBidInfoBySectionId(tradeSecondQuotationBidInfoDto.getSectionId());
        for (BidSectionOfferDTO bidSectionOfferDTO : bidSectionOfferDTOS) {
            bidSectionOfferDTO.setSecBidId(secondQuotationBidInfo.getId().intValue());
            bidSectionOfferDTO.setOfferType(2);
            bidSectionOfferMapper.insert(bidSectionOfferDTO);
        }
        //查询全部列表并返回
        List<TradeSecondQuotationBidInfoDto> secondQuotationBidInfoAll = listSecQuoBidInfoBySectionId(tradeSecondQuotationBidInfoDto.getSectionId());
        for (TradeSecondQuotationBidInfoDto secondQuotationBidInfo1 : secondQuotationBidInfoAll) {
            //查询当前轮次供应商报价信息
            List<BidSectionOfferDTO> bidSectionOfferDTOS1 = bidSectionOfferService.listOfferInfosByturns(secondQuotationBidInfo.getTurns(), secondQuotationBidInfo1.getSectionId());
            secondQuotationBidInfo1.setBidSectionOfferList(bidSectionOfferDTOS1);
        }

        return secondQuotationBidInfoAll;
    }

    /**
     * Description: 根据开标标段id从开标一览表中获取企业报价转化为第一次报价列表
     *
     * @param tradeSecondQuotationBidInfoDto
     * @author: fengbin
     * @date: 2022/2/21 13:20
     * @return: java.util.List<com.hb.core.pojo.project.section.dto.BidSectionOfferDTO>
     */
    @Transactional
    public List<BidSectionOfferDTO> listFirstBidSectionOfferInfo(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfoDto) {
        QueryWrapper<OpeningBidTender> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("section_id", tradeSecondQuotationBidInfoDto.getSectionId());
        List<OpeningBidTender> openingBidTenders = openingBidTenderMapper.selectList(queryWrapper);
        List<BidSectionOfferDTO> bidSectionOfferDTOS = new ArrayList<>();

        // 判断当前标段绑定的招标文件是简易流程还是标准流程  如果是标准流程有可能涉及到淘汰
        BidSection bidSection = bidSectionMapper.selectById(tradeSecondQuotationBidInfoDto.getSectionId());

        BidFileInfo bidFileInfo = bidFileInfoMapper.selectById(bidSection.getFileId());

        for (OpeningBidTender openingBidTender : openingBidTenders) {
            if(null != bidFileInfo && bidFileInfo.getSimpleOrStandard().equals(2)){
                // 查询当前企业是否淘汰
                Integer num = evaluationThirdMapper.countBySectionIdAndOrgIdAndEliminateFlag(tradeSecondQuotationBidInfoDto.getSectionId(), openingBidTender.getOrgId());
                if(num > 0){
                    continue;
                }
            }
            //获取报价,企业名称
            String decryptContent = openingBidTender.getDecryptContent();
            //如果该企业未解密，则不添加
            if (openingBidTender.getDecryptFlag() != 2 && StrUtil.isNotEmpty(decryptContent)){//向供应商标段报价表中保存第一次报价 --------start--------
                BidSectionOfferDTO bidSectionOfferDTO = new BidSectionOfferDTO();
                bidSectionOfferDTO.setOpeningBidId(openingBidTender.getOpeningBidInfoId());
                bidSectionOfferDTO.setSectionId(openingBidTender.getSectionId());
                bidSectionOfferDTO.setOfferId(openingBidTender.getBidderId());
                JSONObject jsonObject = JSONUtil.parseObj(decryptContent);
                Map<String, String> map = Convert.toMap(String.class, String.class, jsonObject);
                log.info("投标人开标一览表解密内容{}", map);
                // 判断开标一览表是 投标报价单位是元还是万元
                String decryptValue = map.get("投标报价小写（元）");
                if(StrUtil.isEmpty(decryptContent)){
                    decryptValue =  map.get("投标报价小写（万元）");
                }
                bidSectionOfferDTO.setParamValue(decryptValue);
                String legalName = map.get("企业名称");
                bidSectionOfferDTO.setOfferName(legalName);
                bidSectionOfferDTO.setOfferOrder(1);
                bidSectionOfferDTO.setCreateTime(LocalDateTime.now());
                //--------保存结束--------------------
                bidSectionOfferDTOS.add(bidSectionOfferDTO);
            }
        }
        return bidSectionOfferDTOS;
    }

    /**
     * Description: 根据开标标段id查询最后一次二次报价信息
     *
     * @param sectionId
     * @author: fengbin
     * @date: 2022/2/22 10:09
     * @return: com.hb.core.pojo.project.section.entity.TradeSecondQuotationBidInfo
     */
    @Override
    public TradeSecondQuotationBidInfoDto selectSecQuoBidInfoBySectionId(Long sectionId) {
        QueryWrapper<TradeSecondQuotationBidInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("section_id", sectionId);
        queryWrapper.orderByDesc("turns");
        queryWrapper.last("limit 1");
        List<TradeSecondQuotationBidInfo> tradeSecondQuotationBidInfos = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(tradeSecondQuotationBidInfos)) {
            return null;
        }
        TradeSecondQuotationBidInfo tradeSecondQuotationBidInfo = tradeSecondQuotationBidInfos.get(0);
        TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfoDto = BeanUtil.toBean(tradeSecondQuotationBidInfo, TradeSecondQuotationBidInfoDto.class);
        return tradeSecondQuotationBidInfoDto;
    }

    @Override
    public List<TradeSecondQuotationBidInfoDto> listSecQuoBidInfoBySectionId(Long sectionId) {
        QueryWrapper<TradeSecondQuotationBidInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("section_id", sectionId);
        queryWrapper.orderByDesc("turns");
        List<TradeSecondQuotationBidInfo> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<TradeSecondQuotationBidInfoDto> convert = Convert.convert(new TypeReference<List<TradeSecondQuotationBidInfoDto>>() {
        }, list);
        return convert;
    }

    /**
     * Description: 专家提交报价信息
     *
     * @param tradeSecondQuotationBidInfo
     * @author: fengbin
     * @date: 2022/2/21 15:56
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean saveSecQuoBidInfo(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfo) {
        //获取最新的标段报价信息
        TradeSecondQuotationBidInfoDto secondQuotationBidInfo = selectSecQuoBidInfoBySectionId(tradeSecondQuotationBidInfo.getSectionId());
        if (ObjectUtils.isEmpty(secondQuotationBidInfo)) {
            return false;
        }

        //修改当前轮次供应商专家意见
//        tradeSecondQuotationBidInfo.getBidSectionOfferList().forEach(bidSectionOfferDTO -> bidSectionOfferService.updataExpertOpinionByOfferId(bidSectionOfferDTO));
        //判断上轮本轮报价是否有为空，有则将报价给为上一轮报价/结束本轮报价
        endTurns(secondQuotationBidInfo);
        //判断是否结束报价进行更新/根据当前轮次及开标标段id查询信息 否则新增
        if (tradeSecondQuotationBidInfo.getEndType().equals(String.valueOf(2))) {
            //修改当前二次报价标段状态
            secondQuotationBidInfo.setEndType("2");
            secondQuotationBidInfo.setEndTime(LocalDateTime.now());
            baseMapper.updateById(secondQuotationBidInfo);
        } else {
            //新增轮次
            tradeSecondQuotationBidInfo.setTurns(secondQuotationBidInfo.getTurns() + 1);
            tradeSecondQuotationBidInfo.setCreateTime(LocalDateTime.now());
            baseMapper.insert(tradeSecondQuotationBidInfo);
            TradeSecondQuotationBidInfoDto secondQuotationBidInfoDto = selectSecQuoBidInfoBySectionId(tradeSecondQuotationBidInfo.getSectionId());
            //获取供应商信息
            List<BidSectionOfferDTO> bidSectionOfferList = bidSectionOfferService.listOfferInfosByturns(1, tradeSecondQuotationBidInfo.getSectionId());
            // 临时使用一下 将获取专家指导意见
            for (BidSectionOfferDTO bidSectionOfferDTO: tradeSecondQuotationBidInfo.getBidSectionOfferList()){
                for (BidSectionOfferDTO bidSectionOfferDTO1: bidSectionOfferList){
                    if (bidSectionOfferDTO.getOfferId().equals(bidSectionOfferDTO1.getOfferId())){
                        bidSectionOfferDTO1.setExpertOpinion(bidSectionOfferDTO.getExpertOpinion());
                    }
                }
            }

            for (BidSectionOffer bidSectionOffer : bidSectionOfferList) {
                //新增下一轮报价
                bidSectionOffer.setId(null);
                bidSectionOffer.setSectionId(secondQuotationBidInfo.getSectionId());
                bidSectionOffer.setEndTime(tradeSecondQuotationBidInfo.getEndTime());
                bidSectionOffer.setOfferOrder(secondQuotationBidInfo.getTurns() + 1);
                bidSectionOffer.setSecBidId(secondQuotationBidInfoDto.getId().intValue());
                bidSectionOffer.setExpertOpinion(bidSectionOffer.getExpertOpinion());
                bidSectionOffer.setCreateTime(LocalDateTime.now());
                bidSectionOffer.setParamValue("");
                bidSectionOffer.setOfferType(1);
                bidSectionOfferMapper.insert(bidSectionOffer);
            }
        }
        return true;
    }

    //结束本轮报价 如果本轮企业没有报价，默认为上轮报价 开始
    public void endTurns(TradeSecondQuotationBidInfoDto dto) {
//       根据轮次和开标标段id获取当前轮次报价信息
        if (dto.getTurns() > 1) {
            List<BidSectionOfferDTO> bidSectionOfferDTOS = bidSectionOfferService.listOfferInfosByturns(dto.getTurns(), dto.getSectionId());
            for (BidSectionOffer bidSectionOffer : bidSectionOfferDTOS) {
                //判断当前报价轮次是否有报价
                if (StrUtil.isEmpty(bidSectionOffer.getParamValue())) {
                    //获取上一轮报价
                    BidSectionOffer lastBidSectionOffer = bidSectionOfferService.getLastBidSectionOffer(dto.getTurns() - 1, bidSectionOffer.getOfferId(), bidSectionOffer.getSectionId());
                    bidSectionOffer.setUpdateTime(LocalDateTime.now());
                    bidSectionOffer.setParamValue(lastBidSectionOffer.getParamValue());
                    bidSectionOffer.setOfferType(2);
                    bidSectionOfferMapper.updateById(bidSectionOffer);
                    log.warn("本轮无报价，默认上一轮报价{}{}", bidSectionOffer, lastBidSectionOffer);
                }
            }
        }
    }

    /**
     * Description: 专家轮询方法
     *
     * @param tradeSecondQuotationBidInfo
     * @author: fengbin
     * @date: 2022/2/22 10:04
     * @return: com.hb.core.pojo.project.section.dto.TradeSecondQuotationBidInfoDto
     */
    @Override
    public List<TradeSecondQuotationBidInfoDto> pollSecQuoBidInfo(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfo) {
        //根据开标标段id查询二次报价标段表信息。若为空则初始化
        //获取全部轮次信息
        List<TradeSecondQuotationBidInfoDto> tradeSecondQuotationBidInfos = listSecQuoBidInfoBySectionId(tradeSecondQuotationBidInfo.getSectionId());
        if (CollUtil.isEmpty(tradeSecondQuotationBidInfos)) {
            return initFirstOfferInfo(tradeSecondQuotationBidInfo);
        }
        for (TradeSecondQuotationBidInfoDto secondQuotationBidInfo : tradeSecondQuotationBidInfos) {
            // 前端展示需要汉字
            secondQuotationBidInfo.setTurnsName(StringUtils.ToCH(secondQuotationBidInfo.getTurns()));
            // 报价截止时间(前端不需要转格式)
            secondQuotationBidInfo.setEndDate(secondQuotationBidInfo.getEndTime());

            //查询当前轮次供应商报价信息
            List<BidSectionOfferDTO> bidSectionOfferDTOS = bidSectionOfferService.listOfferInfosByturns(secondQuotationBidInfo.getTurns(), tradeSecondQuotationBidInfo.getSectionId());
            secondQuotationBidInfo.setBidSectionOfferList(bidSectionOfferDTOS);

            secondQuotationBidInfo.setInQuotation(0);
        }

        TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfoDto = tradeSecondQuotationBidInfos.get(0);
        if (null != tradeSecondQuotationBidInfoDto.getEndType() && tradeSecondQuotationBidInfoDto.getEndType().equals("1")) {
            tradeSecondQuotationBidInfoDto.setInQuotation(1);
        }

        return tradeSecondQuotationBidInfos;
    }

    /**
     * 根据项目Id查询标段报价列表
     *
     * @author yuezhengt
     * @param tradeSecondQuotationBidInfoDto
     * @return org.fzzn.core.model.msg.Message
     * @date 2022/5/17 12:52
     */
    @Override
    public PageResult<TradeSecondQuotationBidInfoDto> listByProjectId(TradeSecondQuotationBidInfoDto tradeSecondQuotationBidInfoDto) {
        Page<TradeSecondQuotationBidInfoDto> pages = tradeSecondQuotationBidInfoDto.pages();
        pages = baseMapper.listByProjectId(pages,tradeSecondQuotationBidInfoDto);
        return  PageResult.get(pages);
    }

    /**
     * 查询多伦报价是否结束
     *
     * @author tian
     * @date 2022-7-1 14:49
     * @param sectionId
     * @return java.lang.Boolean
     */
    @Override
    public Boolean selectEndType(Long sectionId) {
        QueryWrapper<TradeSecondQuotationBidInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("section_id", sectionId);
        queryWrapper.eq("end_type", 2);
        List<TradeSecondQuotationBidInfo> list = baseMapper.selectList(queryWrapper);
        return list.size() > 0 ? true : false;
    }


}
